package com.epalmpay.service.jobservice.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import com.epalmpay.entity.*;
import com.epalmpay.entity.profit.Profit;
import com.epalmpay.entity.profit.ProfitAgentMonth;
import com.epalmpay.entity.profit.ProfitMemberMonth;
import com.epalmpay.entity.profit.ProfitShopMonth;
import com.epalmpay.enumdef.BizEnum;
import com.epalmpay.enumdef.ProfitEnum;
import com.epalmpay.mapper.*;

import com.epalmpay.mapper.profit.*;
import com.epalmpay.service.profitmanage.IProfitManageService;
import com.epalmpay.util.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import com.epalmpay.exception.ApplicationException;
import com.epalmpay.status.Rescode;
import com.epalmpay.enumdef.BizEnum.AgentProfitMode;
import com.epalmpay.enumdef.BizEnum.MemberDevelopeFrom;
import com.epalmpay.enumdef.BizEnum.ProfitCalculateStatus;
import com.epalmpay.enumdef.CommonEnum.RunStatus;
import com.epalmpay.enumdef.CommonEnum.TaskType;
import com.epalmpay.payplat.ComputeProfit;
import com.epalmpay.payplat.IPayAPI;
import com.epalmpay.payplat.result.ComputeProfitResult;
import com.epalmpay.service.jobservice.IProfitStatisService;
import com.epalmpay.util.DateUtil;

/**
 * Created by wzq on 2017/6/14.
 */
@Service("profitStatisServiceImpl")
public class ProfitStatisServiceImpl implements IProfitStatisService{
	@Resource
	GroupConfigMapper groupConfigMapper;	
	@Resource
	TradeOfflineMapper tradeOfflineMapper;	
	@Resource
	MemberMapper memberMapper;	
	//@Resource
	//ShopGroupRelationMapper shopGroupRelationMapper;
	@Resource
	AgentMapper agentMapper;

	@Resource
	private ProfitMapper profitMapper;
	@Resource
	IProfitManageService profitManageService;
	@Resource
	private GroupMapper groupMapper;
	@Resource
    private SysTaskLogMapper sysTaskLogMapper;
	@Resource
	private ProfitMemberDayMapper profitMemberDayMapper;
	@Resource
	private ProfitShopDayDetailMapper profitShopDayDetailMapper;
	@Resource
	private ProfitAgentDayDetailMapper profitAgentDayDetailMapper;
	@Resource
	private ProfitGroupDayDetailMapper profitGroupDayDetailMapper;

	@Resource
	private ProfitMemberMonthMapper profitMemberMonthMapper;
	@Resource
	private ProfitShopMonthDetailMapper profitShopMonthDetailMapper;
	@Resource
	private ProfitShopMonthMapper profitShopMonthMapper;
	@Resource
	private ProfitAgentMonthDetailMapper profitAgentMonthDetailMapper;
	@Resource
	private ProfitAgentMonthMapper profitAgentMonthMapper;
	@Resource
	private ProfitGroupMonthDetailMapper profitGroupMonthDetailMapper;
	@Resource
	private ProfitGroupMonthMapper profitGroupMonthMapper;
    @Resource
	private YsObdProfitRuleMapper ysObdProfitRuleMapper;
    @Resource
	private YsOpenCreditProfitRuleMapper ysOpenCreditProfitRuleMapper;
    @Resource
	private YsPolicyProfitCityMapper ysPolicyProfitCityMapper;
    @Resource
	private YsPolicyProfitRuleMapper ysPolicyProfitRuleMapper;
    @Resource
	private YsShopCarMapper ysShopCarMapper;

	private ExecutorService exec;
	protected Logger logger = Logger.getLogger(this.getClass());

	@Value("${YUNSTREAM_GROUP_ID}")
	private Long ysGroupId;

	@PostConstruct
	public void initialize() {
		exec = Executors.newSingleThreadExecutor();
	}


	//生效月分润比例设置
	public int saveValidProfitSetting(Date statisDate) throws Exception{
		int result=0;
		
		String nowSrt = DateUtil.fomatDate(new Date(),DateUtil.sdfDayss) + "01";
		//比较是否为当前月份
		if(!DateUtil.fomatDate(statisDate, DateUtil.sdfDays).equals(nowSrt)){
			throw new ApplicationException(Rescode.FAIL,"非当前月份不能执行！");
		}
		
    	//查询老记录
    	Map<String,Object> param=new HashMap<String,Object>();
		param.put("taskType", TaskType.ValidProfitSetting.getType());
		param.put("taskDate", statisDate);

		SysTaskLog oldRecord = sysTaskLogMapper.selectSysTaskLogByTypeAndDate(param);
        if(oldRecord  != null && oldRecord.getResultStatus() == RunStatus.Success.getType()){
        	throw new ApplicationException(Rescode.FAIL,"计划任务已经执行成功！");
        }

    	StringBuffer sb = new StringBuffer();
    	//分润比例修改月生效
    	result = groupConfigMapper.updateSaveOldFeeRate(statisDate);
    	sb.append("本次任务【分润比例修改月生效】影响的行数：").append(result);
    	//分润门店日统计
    	result = groupConfigMapper.updateNewFeeRate(statisDate);
    	//更新老值与更新新值结果集数据应该是一样多的

		//代理商分润比率自动生效处理
		result = agentMapper.updateSaveOldFeeRate(statisDate);
		sb.append("本次任务【代理商分润比率修改月生效】影响的行数：").append(result);
		result = agentMapper.updateNewFeeRate(statisDate);
		//代理商预采购分润比率自动生效处理
		result = agentMapper.updateSaveOldPreFeeRate(statisDate);
		sb.append("本次任务【代理商预采购分润比率修改月生效】影响的行数：").append(result);
		result = agentMapper.updateNewPreFeeRate(statisDate);

		//云流门店交易分润比率自动生效处理
		result = ysShopCarMapper.updateSaveOldFeeRate(statisDate);
		sb.append("本次任务【云流门店交易分润比率修改月生效】影响的行数：").append(result);
		result = ysShopCarMapper.updateNewFeeRate(statisDate);
		//云流门店预采购分润比率自动生效处理
		result = ysShopCarMapper.updateSaveOldPreFeeRate(statisDate);
		sb.append("本次任务【云流门店预采购分润比率修改月生效】影响的行数：").append(result);
		result = ysShopCarMapper.updateNewPreFeeRate(statisDate);

		//云流OBD分润比率自动生效
		result = ysObdProfitRuleMapper.updateSaveOldFeeRate(statisDate);
		sb.append("本次任务【云流OBD分润比率修改月生效】影响的行数：").append(result);
		result = ysObdProfitRuleMapper.updateNewFeeRate(statisDate);

		//云流信用卡开卡分润比率自动生效
		result = ysOpenCreditProfitRuleMapper.updateSaveOldFeeRate(statisDate);
		sb.append("本次任务【云流信用卡开卡分润比率修改月生效】影响的行数：").append(result);
		result = ysOpenCreditProfitRuleMapper.updateNewFeeRate(statisDate);

		//云流保单分润比率自动生效
		result = ysPolicyProfitCityMapper.updateSaveOldFeeRate(statisDate);
		sb.append("本次任务【云流保单分润比率修改月生效】影响的行数：").append(result);
		result = ysPolicyProfitCityMapper.updateNewFeeRate(statisDate);
		result = ysPolicyProfitRuleMapper.updateSaveOldFeeRate(statisDate);
		sb.append("本次任务【云流保单分润比率修改月生效】影响的行数：").append(result);
		result = ysPolicyProfitRuleMapper.updateNewFeeRate(statisDate);

    	//插入计划任务成功日志
        if(oldRecord  == null){
	    	SysTaskLog record = new SysTaskLog();
	    	record.setGmtCreate(new Date());
	    	record.setGmtModified(new Date());
	    	record.setTaskType(TaskType.ValidProfitSetting.getType());
	    	record.setTaskDate(statisDate);
	    	record.setResultStatus(RunStatus.Success.getType());
	    	record.setRunTimes(0);
	    	record.setMemo(sb.toString());
	    	result = sysTaskLogMapper.insert(record);
        }
        else{
        	oldRecord.setGmtModified(new Date());
        	oldRecord.setResultStatus(RunStatus.Success.getType());
        	oldRecord.setRunTimes((oldRecord.getRunTimes()==null?0:oldRecord.getRunTimes())+1);
        	oldRecord.setMemo(sb.toString());
        	result = sysTaskLogMapper.updateByPrimaryKeySelective(oldRecord);
        }		
		
		return result;
	}

	//查询需要分润的交易记录	
	public List<TradeOffline> selectNeedProfitList(Date selectDate) throws Exception{
		return tradeOfflineMapper.selectNeedProfitList(selectDate);
	}

	/***单笔交易分润计算
	 * 代理商分润：
	 *    (1)钱包交易根据商家手续费分润；
	 *    (2)线下交易：
			 固定3级分润计算公式:
			 假设一级设置50%，二级设置30%，三级设置10%；可分润金额为100元
			 一级代理商可得金额为100元X（50%-30%）=20元
			 二级代理商可得金额为100元X（30%-10%）=20元
			 三级代理商可得金额为100元X10%=10元
	         固定3级计算根据各级相减计算
	         流动3级根据设置的比例直接计算
	      (3)预采购交易：
	         同渠道设置，一级代理可修改分润比率
	 * @param record
	 * @return
	 * @throws Exception
	 */
    @Override
	public int saveOneOrderProfitCalculate(TradeOffline record) throws Exception{
    	int result=0;
        StringBuffer sb = new StringBuffer();

        Integer profitAmount = 0;

		try {
            record.setAttachStatus(record.getAttachStatus()==null?0:record.getAttachStatus());
			if(record.getAttachStatus()==ProfitCalculateStatus.CalculateFinished.getType()) {
				System.out.println("此笔交易"+ record.getId()+"已经分润，不能再次分润!");
				//return 0;
			}
			//预采购分润
			if("Prepurchase".equals(record.getMemo()) && ysGroupId.equals(record.getGroupId())) {//预采购云流分润
				result = oneOrderYunStreamPrechuseProfitCalculate(record);
				return result;
			}else if("Prepurchase".equals(record.getMemo())){//预采购分润
				result = oneOrderPrechuseProfitCalculate(record);
				return result;
			}
			//云流交易分润
			if(ysGroupId.equals(record.getGroupId())) {
				result = oneOrderYunStreamProfitCalculate(record);
				return result;
			}
			//交易分润
			result = oneOrderProfitCalculate(record);

		}catch (DuplicateKeyException dke){
			System.out.println("此笔交易"+ record.getId()+"已经分润，不能再次分润!");
		}
		catch (Exception e) {
			e.printStackTrace();
		}

    	return result;
    }
    
    /***
     * 消费分润计算,获取可分金额
     * @param record
     * @return
     * @throws Exception
     */
    public int oneOrderProfitCalculate(TradeOffline record) throws Exception{

		Integer profitAmount = 0;

		if(record.getPayType() == BizEnum.PaymentType.Wallet.getType()){
			profitAmount = record.getShopFee();
		}else{
			profitAmount = callPayPlatfromGetProfit(record);
		}

		//Integer profitAmount = 10000;
		if(profitAmount == null || profitAmount <= 0 ){
			System.out.println("分润总额不能小于等于0!");
			return 0;
			
		}
	 return	oneOrderProfitCalculate(record, profitAmount);
    }
    /**
     * 根据分润体系，完成各种角色的分润
     * @param record
     * @param profitAmount
     * @return
     * @throws Exception
     */
    //正常的交易分润
	public int oneOrderProfitCalculate(TradeOffline record, Integer profitAmount) throws Exception{
		int result=0;
		Date date = new Date();
		Profit profit = new Profit();
		profit.setGmtCreate(date);
		profit.setGmtModified(date);
		profit.setGroupId(record.getGroupId());
		profit.setProfitType(ProfitEnum.ProfitType.Transaction.getType());
		profit.setProfit(profitAmount);
		profit.setProduceShopid(Long.parseLong(record.getReceiverId()));
		profit.setProduceMemberid(record.getPayerId());

		//查询分润比例
		GroupConfig groupConfig = groupConfigMapper.getSystemParamsByGroupId(record.getGroupId());
		//
		Integer mfirst_fee_rate = 0;
		Integer msecond_fee_rate = 0;
		Integer merchant_fee_rate = 0;
		Integer first_fee_rate = 0;
		Integer second_fee_rate = 0;
		Integer third_fee_rate = 0;

		//如果有效期时间大于修改时间且交易月分
		String tradeMonth = DateUtil.fomatDate(record.getGmtCreate(), DateUtil.sdfDayss);
		if(groupConfig.getValidTime() != null && groupConfig.getValidTime().compareTo(groupConfig.getGmtModified()) > 0
				&& tradeMonth.equals(DateUtil.fomatDate(groupConfig.getGmtModified(), DateUtil.sdfDayss))){
			//取老值
			mfirst_fee_rate = groupConfig.getOldMfirstFeeRate()==null?0:groupConfig.getOldMfirstFeeRate();
			msecond_fee_rate = groupConfig.getOldMsecondFeeRate()==null?0:groupConfig.getOldMsecondFeeRate();
			merchant_fee_rate = groupConfig.getOldMerchantFeeRate()==null?0:groupConfig.getOldMerchantFeeRate();
			first_fee_rate = groupConfig.getOldFirstFeeRate()==null?0:groupConfig.getOldFirstFeeRate();
			second_fee_rate = groupConfig.getOldSecondFeeRate()==null?0:groupConfig.getOldSecondFeeRate();
			third_fee_rate = groupConfig.getOldThirdFeeRate()==null?0:groupConfig.getOldThirdFeeRate();
		}else{
			mfirst_fee_rate = groupConfig.getMfirstFeeRate()==null?0:groupConfig.getMfirstFeeRate();
			msecond_fee_rate = groupConfig.getMsecondFeeRate()==null?0:groupConfig.getMsecondFeeRate();
			merchant_fee_rate = groupConfig.getMerchantFeeRate()==null?0:groupConfig.getMerchantFeeRate();
			first_fee_rate = groupConfig.getFirstFeeRate()==null?0:groupConfig.getFirstFeeRate();
			second_fee_rate = groupConfig.getSecondFeeRate()==null?0:groupConfig.getSecondFeeRate();
			third_fee_rate = groupConfig.getThirdFeeRate()==null?0:groupConfig.getThirdFeeRate();
		}

		//会员发展返利计算(发展会员与推荐会员计算)
		Member member = memberMapper.selectDevelopeFromInfoByPrimaryKey(record.getPayerId());
		if(member!=null && member.getFromType()==MemberDevelopeFrom.UserDevelope.getType()
				&& groupConfig.getRecommendedPersonMode()==1){
			Integer mfirstProfit = Math.round(profitAmount*mfirst_fee_rate/100);
			//Integer mfirstProfit = Math.round(profitAmount*mfirst_fee_rate);
			if(mfirstProfit>0){
				profit.setMemberId(member.getFromId());
				profit.setDevelopeProfit(mfirstProfit);
			}
			Member secondMember = memberMapper.selectDevelopeFromInfoByPrimaryKey(member.getFromId());
			if(secondMember!=null && secondMember.getFromType()==MemberDevelopeFrom.UserDevelope.getType()){
				Integer msecondProfit = Math.round(profitAmount*msecond_fee_rate/100);
				//Integer msecondProfit = Math.round(profitAmount*msecond_fee_rate);
				if(msecondProfit>0){
					profit.setRecommendMemberId(secondMember.getFromId());
					profit.setRecommendProfit(msecondProfit);
				}
			}
		}

		//商家分润计算(已开户且非本店)
		if(groupConfig.getMemberFeeMode() ==1 && member.getFromType() != null
				&&member.getFromType()==MemberDevelopeFrom.ShopDevelope.getType()
				&& !member.getFromId().equals(Long.parseLong(record.getReceiverId()))){
			Integer shopProfit = Math.round(profitAmount*merchant_fee_rate/100);
			//Integer shopProfit = Math.round(profitAmount*merchant_fee_rate);
			if(shopProfit>0){
				profit.setShopId(member.getFromId());
				profit.setShopProfit(shopProfit);
			}
		}

		//代理分润计算
		//获得本级代理
		Agent firstAgent = agentMapper.selectAgentProfitInfoByShopId(Long.parseLong(record.getReceiverId()),record.getGroupId());
		if(firstAgent!=null){
			Integer firstAgentProfit = 0;
			Integer firstFeeRate = 0;
			if(groupConfig.getAgentMode() == AgentProfitMode.ScrollThreeLevel.getType()){
				firstFeeRate = third_fee_rate;
				firstAgentProfit = Math.round(profitAmount*firstFeeRate/100);
			}else if(groupConfig.getAgentMode() == AgentProfitMode.FixedThreeLevel.getType()){
				firstFeeRate = firstAgent.getValidProfitRate(record.getGmtCreate());
				firstAgentProfit = Math.round(profitAmount*firstFeeRate/100);
			}
			//Integer firstAgentProfit = Math.round(profitAmount*firstFeeRate);
			if(firstAgentProfit>0){
				if(firstAgent.getAgentLevel() == 3){
					profit.setThirdAgentId(firstAgent.getId());
					profit.setThirdAgentProfit(firstAgentProfit);
				}else if(firstAgent.getAgentLevel() == 2){
					profit.setSecondAgentId(firstAgent.getId());
					profit.setSecondAgentProfit(firstAgentProfit);
				}else if(firstAgent.getAgentLevel() == 1){
					profit.setFirstAgentId(firstAgent.getId());
					profit.setFirstAgentProfit(firstAgentProfit);
				}
			}
			//获得本级的上级代理
			Agent secondAgent = agentMapper.selectParentAgentProfitInfoById(firstAgent.getId());
			if(secondAgent!=null){
				Integer secondAgentProfit = 0;
				Integer secondFeeRate = 0;
				if(groupConfig.getAgentMode() == AgentProfitMode.ScrollThreeLevel.getType()){
					secondFeeRate = second_fee_rate;
					secondAgentProfit = Math.round(profitAmount*secondFeeRate/100);
				}else if(groupConfig.getAgentMode() == AgentProfitMode.FixedThreeLevel.getType()){
					secondFeeRate = secondAgent.getValidProfitRate(record.getGmtCreate());
					secondAgentProfit = Math.round(profitAmount*(secondFeeRate-firstFeeRate)/100);
				}
				//Integer secondAgentProfit = Math.round(profitAmount*(secondFeeRate-firstFeeRate));
				if(secondAgentProfit>0){
					if(secondAgent.getAgentLevel() == 2){
						profit.setSecondAgentId(secondAgent.getId());
						profit.setSecondAgentProfit(secondAgentProfit);
					}else if(secondAgent.getAgentLevel() == 1){
						profit.setFirstAgentId(secondAgent.getId());
						profit.setFirstAgentProfit(secondAgentProfit);
					}
				}
				//获得本级的上级的上级代理
				Agent thirdAgent = agentMapper.selectParentAgentProfitInfoById(secondAgent.getId());
				if(thirdAgent!=null){
					Integer thirdAgentProfit = 0;
					Integer thirdFeeRate = 0;
					if(groupConfig.getAgentMode() == AgentProfitMode.ScrollThreeLevel.getType()){
						thirdFeeRate = first_fee_rate;
						thirdAgentProfit = Math.round(profitAmount*thirdFeeRate/100);
					}else if(groupConfig.getAgentMode() == AgentProfitMode.FixedThreeLevel.getType()){
						thirdFeeRate = thirdAgent.getValidProfitRate(record.getGmtCreate());
						thirdAgentProfit = Math.round(profitAmount*(thirdFeeRate - secondFeeRate)/100);
					}
					//Integer thirdAgentProfit = Math.round(profitAmount*(thirdFeeRate - secondFeeRate));
					if(thirdAgentProfit>0){
						if(thirdAgent.getAgentLevel() == 1){
							profit.setFirstAgentId(thirdAgent.getId());
							profit.setFirstAgentProfit(thirdAgentProfit);
						}
					}
				}
			}
		}

		profit.setProfitStatus(ProfitEnum.ProfitStatus.Profited.getType());
		profit.setOrderId(record.getId());
		profit.setOrderNo(record.getOrderId());

		result = profitMapper.insert(profit);

		//更新交易分润状态
		TradeOffline updateRecord = new TradeOffline();
		updateRecord.setId(record.getId());
		updateRecord.setGmtModified(new Date());
		updateRecord.setDividableAmount(profitAmount);
		updateRecord.setAttachStatus(ProfitCalculateStatus.CalculateFinished.getType());
		tradeOfflineMapper.updateByPrimaryKeySelective(updateRecord);

		return result;

	}

	//云流交易分润
	public int oneOrderYunStreamProfitCalculate(TradeOffline record) throws Exception{
		int result=0;
		StringBuffer sb = new StringBuffer();

		Integer profitAmount = 0;

		if(record.getPayType() == BizEnum.PaymentType.Wallet.getType()){
			profitAmount = record.getShopFee();
		}else{
			profitAmount = callPayPlatfromGetProfit(record);
		}

		//Integer profitAmount = 10000;
		if(profitAmount == null || profitAmount <= 0 ){
			System.out.println("分润总额不能小于等于0!");
			return 0;
			//throw new ApplicationException("分润金额为空！");
			//return 0;
		}

		Date date = new Date();
		Profit profit = new Profit();
		profit.setGmtCreate(date);
		profit.setGmtModified(date);
		profit.setGroupId(record.getGroupId());
		profit.setProfitType(ProfitEnum.ProfitType.Transaction.getType());
		profit.setProfit(profitAmount);
		profit.setProduceShopid(Long.parseLong(record.getReceiverId()));
		profit.setProduceMemberid(record.getPayerId());

		//查询分润比例
		GroupConfig groupConfig = groupConfigMapper.getSystemParamsByGroupId(record.getGroupId());
		Integer merchant_fee_rate = 0;
		//如果有效期时间大于修改时间且交易月分
		String tradeMonth = DateUtil.fomatDate(record.getGmtCreate(), DateUtil.sdfDayss);
		if(groupConfig.getValidTime() != null && groupConfig.getValidTime().compareTo(groupConfig.getGmtModified()) > 0
				&& tradeMonth.equals(DateUtil.fomatDate(groupConfig.getGmtModified(), DateUtil.sdfDayss))){
			//取老值
			merchant_fee_rate = groupConfig.getOldMerchantFeeRate()==null?0:groupConfig.getOldMerchantFeeRate();
		}else{
			merchant_fee_rate = groupConfig.getMerchantFeeRate()==null?0:groupConfig.getMerchantFeeRate();
		}

		//取得门店分润信息
		YsShopCar ysShopCar = ysShopCarMapper.selectShopProfitInfoById(Long.parseLong(record.getReceiverId()));
		if(ysShopCar == null) {
			System.out.println("门店(" + record.getReceiverId() + ")分润信息未设置!");
			return 0;
		}

		Long firstAgentId = 0l;
		Integer firstAgentProfit = 0;
		Integer firstFeeRate = 0;

		Long secondAgentId = 0l;
		Integer secondAgentProfit = 0;
		Integer secondFeeRate = 0;

		Integer shopFeeRate = 0;
		Integer shopProfit = 0;

		Integer recommendShopProfit = 0;

		shopFeeRate = ysShopCar.getValidProfitRate(record.getGmtCreate());
		shopProfit = Math.round(profitAmount*shopFeeRate/100);

		//代理分润计算
		//获得门店上级代理
		Agent parentAgent = agentMapper.selectAgentProfitInfoByShopId(Long.parseLong(record.getReceiverId()),record.getGroupId());
		if(parentAgent!=null){
			if(parentAgent.getAgentLevel() == 1){
				firstFeeRate = parentAgent.getValidProfitRate(record.getGmtCreate());
				firstAgentProfit = Math.round(profitAmount*(firstFeeRate-shopFeeRate)/100);
				firstAgentId = parentAgent.getId();
			}else if(parentAgent.getAgentLevel() == 2){
				Agent grandpaAgent = agentMapper.selectParentAgentProfitInfoById(parentAgent.getId());
				if(grandpaAgent.getAgentLevel() == 1){
					secondFeeRate = parentAgent.getValidProfitRate(record.getGmtCreate());
					secondAgentProfit = Math.round(profitAmount*(secondFeeRate-shopFeeRate)/100);
					secondAgentId = parentAgent.getId();
					firstFeeRate = grandpaAgent.getValidProfitRate(record.getGmtCreate());
					firstAgentProfit = Math.round(profitAmount*(firstFeeRate-secondFeeRate)/100);
					firstAgentId = grandpaAgent.getId();
				}
			}
		}
		//跨门店分润商家分润计算(已开户且非本店)
		Member member = memberMapper.selectDevelopeFromInfoByPrimaryKey(record.getPayerId());
		if(groupConfig.getMemberFeeMode() ==1 && member.getFromType() != null
				&& member.getFromType()==MemberDevelopeFrom.ShopDevelope.getType()
				&& !member.getFromId().equals(Long.parseLong(record.getReceiverId()))){
			recommendShopProfit = Math.round(profitAmount*merchant_fee_rate/100);
			if(recommendShopProfit>0){
				profit.setRecommendShopId(member.getFromId());
			}
		}

		profit.setFirstAgentId(firstAgentId);
		profit.setFirstAgentProfit(firstAgentProfit);
		profit.setSecondAgentId(secondAgentId);
		profit.setSecondAgentProfit(secondAgentProfit);
		profit.setShopId(ysShopCar.getShopId());
		profit.setShopProfit(shopProfit);
		profit.setRecommendShopProfit(recommendShopProfit);

		profit.setProfitStatus(ProfitEnum.ProfitStatus.Profited.getType());
		profit.setProduceShopid(ysShopCar.getShopId());
		profit.setProduceMemberid(record.getPayerId());
		profit.setOrderId(record.getId());
		profit.setOrderNo(record.getOrderId());
		result = profitMapper.insert(profit);

		//更新交易分润状态
		TradeOffline updateRecord = new TradeOffline();
		updateRecord.setId(record.getId());
		updateRecord.setGmtModified(new Date());
		//updateRecord.setDividableAmount(profitAmount);
		updateRecord.setAttachStatus(ProfitCalculateStatus.CalculateFinished.getType());
		tradeOfflineMapper.updateByPrimaryKeySelective(updateRecord);

		return result;
	}

	private Integer callPayPlatfromGetProfit(TradeOffline record) throws Exception{

    	StringBuffer sb = new StringBuffer();

		//支付方式转换
		int payType = 0;
		//现金消费不计算分润
		if(record.getPayType() == null || record.getPayType() == BizEnum.PaymentType.Cash.getType())
			return 0;
		switch (BizEnum.PaymentType.fromType(record.getPayType())){
			case BankCard:
				payType = 1;
				break;
			case WebChat:
				payType = 2;
				break;
			case AliPay:
				payType = 3;
				break;
			case Baidu:
				payType = 4;
				break;
			case Jd:
				payType = 5;
				break;
			case NetBankCard:
				payType = 6;
				break;
			case NetBankCardQuick:
				payType = 7;
				break;
			case UnionBank:
				payType =8;
				break;
			default:
				break;
		}
		//支付渠道转换(扫码付通道标识)
		int payChannel = 0;
		if(record.getScanOrganization()!=null) {
			switch (BizEnum.ScanInNetCompany.fromType(record.getScanOrganization())) {
				case shouqianba:
					payChannel = 266;
					break;
				case fuqianla:
					payChannel = 265;
					break;
				default:
					break;
			}
		}
		Group group = groupMapper.selectPayCodeById(record.getGroupId());
		//查询华尔街平台计算分润金额
		ComputeProfit computeProfit = ComputeProfit.initialize(record.getTermSerial(),
				record.getMerchantNo(),record.getTerminalNo(),
				payType==0?null:String.valueOf(payType), record.getRealAmount().toString(),
				record.getPayAccount()==null?null:record.getPayAccount(), payChannel==0?null:String.valueOf(payChannel),
				group.getPayGroupCode());
		ComputeProfitResult profitResult = IPayAPI.finishComputeProfit(computeProfit);
		if(!profitResult.getRespCode().equals("0000")) {
			throw new ApplicationException(Rescode.FAIL,sb.append("计算分润金额调用华尔街平台接口失败。(TradeOfflineID:")
					.append(record.getId()).append(")").toString());
		}

		Integer profitAmount = Integer.parseInt(profitResult.getProfitAmount());

         return profitAmount;
	}

	public int oneOrderPrechuseProfitCalculate(TradeOffline record) throws Exception{
		int result=0;
		StringBuffer sb = new StringBuffer();

		Integer profitAmount = 0;
		profitAmount = record.getDividableAmount();

		//Integer profitAmount = 10000;
		if(profitAmount == null || profitAmount <= 2 ){
			System.out.println("分润总额不能小于等于2!");
			return 0;
			//throw new ApplicationException("分润金额为空！");
			//return 0;
		}

		//if(profitAmount>=0)
		//	return 0;
		Date date = new Date();
		Profit profit = new Profit();
		profit.setGmtCreate(date);
		profit.setGmtModified(date);
		profit.setGroupId(record.getGroupId());
		profit.setProfitType(ProfitEnum.ProfitType.Prepurchase.getType());
		profit.setProfit(profitAmount);
		profit.setProduceShopid(Long.parseLong(record.getReceiverId()));
		profit.setProduceMemberid(record.getPayerId());

		//查询分润比例
		GroupConfig groupConfig = groupConfigMapper.getSystemParamsByGroupId(record.getGroupId());

		Integer mfirst_fee_rate = 0;
		Integer msecond_fee_rate = 0;
		Integer merchant_fee_rate = 0;
		Integer first_fee_rate = 0;
		Integer second_fee_rate = 0;
		Integer third_fee_rate = 0;

		//如果有效期时间大于修改时间且交易月分
		String tradeMonth = DateUtil.fomatDate(record.getGmtCreate(), DateUtil.sdfDayss);
		if(groupConfig.getValidTime() != null && groupConfig.getValidTime().compareTo(groupConfig.getGmtModified()) > 0
				&& tradeMonth.equals(DateUtil.fomatDate(groupConfig.getGmtModified(), DateUtil.sdfDayss))){
			//取老值
			mfirst_fee_rate = groupConfig.getOldMfirstFeeRate()==null?0:groupConfig.getOldMfirstFeeRate();
			msecond_fee_rate = groupConfig.getOldMsecondFeeRate()==null?0:groupConfig.getOldMsecondFeeRate();
			merchant_fee_rate = groupConfig.getOldMerchantFeeRate()==null?0:groupConfig.getOldMerchantFeeRate();
		}else{
			mfirst_fee_rate = groupConfig.getMfirstFeeRate()==null?0:groupConfig.getMfirstFeeRate();
			msecond_fee_rate = groupConfig.getMsecondFeeRate()==null?0:groupConfig.getMsecondFeeRate();
			merchant_fee_rate = groupConfig.getMerchantFeeRate()==null?0:groupConfig.getMerchantFeeRate();
		}

		//会员发展返利计算(发展会员与推荐会员计算)
		Member member = memberMapper.selectDevelopeFromInfoByPrimaryKey(record.getPayerId());
		if(member!=null && member.getFromType() != null && member.getFromType()==MemberDevelopeFrom.UserDevelope.getType()
				&& groupConfig.getRecommendedPersonMode()==1){
			Integer mfirstProfit = Math.round(profitAmount*mfirst_fee_rate/100);
			//Integer mfirstProfit = Math.round(profitAmount*mfirst_fee_rate);
			if(mfirstProfit>0){
				profit.setMemberId(member.getFromId());
				profit.setDevelopeProfit(mfirstProfit);
			}
			Member secondMember = memberMapper.selectDevelopeFromInfoByPrimaryKey(member.getFromId());
			if(secondMember!=null && secondMember.getFromType() != null && secondMember.getFromType()==MemberDevelopeFrom.UserDevelope.getType()){
				Integer msecondProfit = Math.round(profitAmount*msecond_fee_rate/100);
				//Integer msecondProfit = Math.round(profitAmount*msecond_fee_rate);
				if(msecondProfit>0){
					profit.setRecommendMemberId(secondMember.getFromId());
					profit.setRecommendProfit(msecondProfit);
				}
			}
		}

		//商家分润计算(已开户且非本店)
		if(groupConfig.getMemberFeeMode() ==1 && member.getFromType() != null
				&&member.getFromType()==MemberDevelopeFrom.ShopDevelope.getType()
				&& !member.getFromId().equals(Long.parseLong(record.getReceiverId()))){
			Integer shopProfit = Math.round(profitAmount*merchant_fee_rate/100);
			//Integer shopProfit = Math.round(profitAmount*merchant_fee_rate);
			if(shopProfit>0){
				profit.setShopId(member.getFromId());
				profit.setShopProfit(shopProfit);
			}
		}

		//代理分润计算
		//获得本级代理
		Agent firstAgent = agentMapper.selectAgentPreprofitInfoByShopId(Long.parseLong(record.getReceiverId()),record.getGroupId());
		if(firstAgent!=null){
			Integer firstAgentProfit = 0;
			Integer firstFeeRate = 0;
			if(groupConfig.getAgentMode() == AgentProfitMode.ScrollThreeLevel.getType()){
				//firstFeeRate = third_fee_rate;
				//firstAgentProfit = Math.round(profitAmount*firstFeeRate/100);
			}else if(groupConfig.getAgentMode() == AgentProfitMode.FixedThreeLevel.getType()){
				firstFeeRate = firstAgent.getValidPreProfitRate(record.getGmtCreate());
				firstAgentProfit = Math.round(profitAmount*firstFeeRate/100);
			}
			//Integer firstAgentProfit = Math.round(profitAmount*firstFeeRate);
			if(firstAgentProfit>0){
				if(firstAgent.getAgentLevel() == 3){
					profit.setThirdAgentId(firstAgent.getId());
					profit.setThirdAgentProfit(firstAgentProfit);
				}else if(firstAgent.getAgentLevel() == 2){
					profit.setSecondAgentId(firstAgent.getId());
					profit.setSecondAgentProfit(firstAgentProfit);
				}else if(firstAgent.getAgentLevel() == 1){
					profit.setFirstAgentId(firstAgent.getId());
					profit.setFirstAgentProfit(firstAgentProfit);
				}
			}
			//获得本级的上级代理
			Agent secondAgent = agentMapper.selectParentAgentPreprofitInfoById(firstAgent.getId());
			if(secondAgent!=null){
				Integer secondAgentProfit = 0;
				Integer secondFeeRate = 0;
				if(groupConfig.getAgentMode() == AgentProfitMode.ScrollThreeLevel.getType()){
					//secondFeeRate = second_fee_rate;
					//secondAgentProfit = Math.round(profitAmount*secondFeeRate/100);
				}else if(groupConfig.getAgentMode() == AgentProfitMode.FixedThreeLevel.getType()){
					secondFeeRate = secondAgent.getValidPreProfitRate(record.getGmtCreate());
					secondAgentProfit = Math.round(profitAmount*(secondFeeRate-firstFeeRate)/100);
				}
				//Integer secondAgentProfit = Math.round(profitAmount*(secondFeeRate-firstFeeRate));
				if(secondAgentProfit>0){
					if(secondAgent.getAgentLevel() == 2){
						profit.setSecondAgentId(secondAgent.getId());
						profit.setSecondAgentProfit(secondAgentProfit);
					}else if(secondAgent.getAgentLevel() == 1){
						profit.setFirstAgentId(secondAgent.getId());
						profit.setFirstAgentProfit(secondAgentProfit);
					}
				}
				//获得本级的上级的上级代理
				Agent thirdAgent = agentMapper.selectParentAgentPreprofitInfoById(secondAgent.getId());
				if(thirdAgent!=null){
					Integer thirdAgentProfit = 0;
					Integer thirdFeeRate = 0;
					if(groupConfig.getAgentMode() == AgentProfitMode.ScrollThreeLevel.getType()){
						//thirdFeeRate = first_fee_rate;
						//thirdAgentProfit = Math.round(profitAmount*thirdFeeRate/100);
					}else if(groupConfig.getAgentMode() == AgentProfitMode.FixedThreeLevel.getType()){
						thirdFeeRate = thirdAgent.getValidPreProfitRate(record.getGmtCreate());
						thirdAgentProfit = Math.round(profitAmount*(thirdFeeRate - secondFeeRate)/100);
					}
					//Integer thirdAgentProfit = Math.round(profitAmount*(thirdFeeRate - secondFeeRate));
					if(thirdAgentProfit>0){
						if(thirdAgent.getAgentLevel() == 1){
							profit.setFirstAgentId(thirdAgent.getId());
							profit.setFirstAgentProfit(thirdAgentProfit);
						}
					}
				}
			}
		}
		profit.setProfitStatus(ProfitEnum.ProfitStatus.Profited.getType());
		profit.setOrderId(record.getId());
		profit.setOrderNo(record.getOrderId());

		result = profitMapper.insert(profit);

		//更新交易分润状态
		TradeOffline updateRecord = new TradeOffline();
		updateRecord.setId(record.getId());
		updateRecord.setGmtModified(new Date());
		//updateRecord.setDividableAmount(profitAmount);
		updateRecord.setAttachStatus(ProfitCalculateStatus.CalculateFinished.getType());
		tradeOfflineMapper.updateByPrimaryKeySelective(updateRecord);

		return result;
	}

	//云流预采购分润
	public int oneOrderYunStreamPrechuseProfitCalculate(TradeOffline record) throws Exception{
		int result=0;
		StringBuffer sb = new StringBuffer();

		Integer profitAmount = 0;
		profitAmount = record.getDividableAmount();

		//Integer profitAmount = 10000;
		if(profitAmount == null || profitAmount <= 2 ){
			System.out.println("分润总额不能小于等于2!");
			return 0;
		}

		//if(profitAmount>=0)
		//	return 0;
		Date date = new Date();
		Profit profit = new Profit();
		profit.setGmtCreate(date);
		profit.setGmtModified(date);
		profit.setGroupId(record.getGroupId());
		profit.setProfitType(ProfitEnum.ProfitType.Prepurchase.getType());
		profit.setProfit(profitAmount);
		profit.setProduceShopid(Long.parseLong(record.getReceiverId()));
		profit.setProduceMemberid(record.getPayerId());

		//查询分润比例
		GroupConfig groupConfig = groupConfigMapper.getSystemParamsByGroupId(record.getGroupId());
		Integer merchant_fee_rate = 0;
		//如果有效期时间大于修改时间且交易月分
		String tradeMonth = DateUtil.fomatDate(record.getGmtCreate(), DateUtil.sdfDayss);
		if(groupConfig.getValidTime() != null && groupConfig.getValidTime().compareTo(groupConfig.getGmtModified()) > 0
				&& tradeMonth.equals(DateUtil.fomatDate(groupConfig.getGmtModified(), DateUtil.sdfDayss))){
			//取老值
			merchant_fee_rate = groupConfig.getOldMerchantFeeRate()==null?0:groupConfig.getOldMerchantFeeRate();
		}else{
			merchant_fee_rate = groupConfig.getMerchantFeeRate()==null?0:groupConfig.getMerchantFeeRate();
		}

        //取得门店分润信息
		YsShopCar ysShopCar = ysShopCarMapper.selectShopPreprofitInfoById(Long.parseLong(record.getReceiverId()));
		if(ysShopCar == null) {
			System.out.println("门店(" + record.getReceiverId() + ")分润信息未设置!");
			return 0;
		}

		Long firstAgentId = 0l;
		Integer firstAgentProfit = 0;
		Integer firstFeeRate = 0;

		Long secondAgentId = 0l;
		Integer secondAgentProfit = 0;
		Integer secondFeeRate = 0;

		Integer shopFeeRate = 0;
		Integer shopProfit = 0;

		Integer recommendShopProfit = 0;

		shopFeeRate = ysShopCar.getValidPreProfitRate(record.getGmtCreate());
		shopProfit = Math.round(profitAmount*shopFeeRate/100);

		//代理分润计算
		//获得门店上级代理
		Agent parentAgent = agentMapper.selectAgentPreprofitInfoByShopId(Long.parseLong(record.getReceiverId()),record.getGroupId());
		if(parentAgent!=null){
			if(parentAgent.getAgentLevel() == 1){
				firstFeeRate = parentAgent.getValidPreProfitRate(record.getGmtCreate());
				firstAgentProfit = Math.round(profitAmount*(firstFeeRate-shopFeeRate)/100);
				firstAgentId = parentAgent.getId();
			}else if(parentAgent.getAgentLevel() == 2){
				Agent grandpaAgent = agentMapper.selectParentAgentPreprofitInfoById(parentAgent.getId());
				if(grandpaAgent.getAgentLevel() == 1){
					secondFeeRate = parentAgent.getValidPreProfitRate(record.getGmtCreate());
					secondAgentProfit = Math.round(profitAmount*(secondFeeRate-shopFeeRate)/100);
					secondAgentId = parentAgent.getId();
					firstFeeRate = grandpaAgent.getValidPreProfitRate(record.getGmtCreate());
					firstAgentProfit = Math.round(profitAmount*(firstFeeRate-secondFeeRate)/100);
					firstAgentId = grandpaAgent.getId();
				}
			}
		}
		//跨门店分润商家分润计算(已开户且非本店)
		Member member = memberMapper.selectDevelopeFromInfoByPrimaryKey(record.getPayerId());
		if(groupConfig.getMemberFeeMode() ==1 && member.getFromType() != null
				&& member.getFromType()==MemberDevelopeFrom.ShopDevelope.getType()
				&& !member.getFromId().equals(Long.parseLong(record.getReceiverId()))){
			recommendShopProfit = Math.round(profitAmount*merchant_fee_rate/100);
			if(recommendShopProfit>0){
				profit.setRecommendShopId(member.getFromId());
			}
		}

		profit.setFirstAgentId(firstAgentId);
        profit.setFirstAgentProfit(firstAgentProfit);
		profit.setSecondAgentId(secondAgentId);
		profit.setSecondAgentProfit(secondAgentProfit);
		profit.setShopId(ysShopCar.getShopId());
		profit.setShopProfit(shopProfit);
		profit.setRecommendShopProfit(recommendShopProfit);

		profit.setProfitStatus(ProfitEnum.ProfitStatus.Profited.getType());
		profit.setProduceShopid(ysShopCar.getShopId());
		profit.setProduceMemberid(record.getPayerId());
		profit.setOrderId(record.getId());
		profit.setOrderNo(record.getOrderId());
		result = profitMapper.insert(profit);

		//更新交易分润状态
		TradeOffline updateRecord = new TradeOffline();
		updateRecord.setId(record.getId());
		updateRecord.setGmtModified(new Date());
		//updateRecord.setDividableAmount(profitAmount);
		updateRecord.setAttachStatus(ProfitCalculateStatus.CalculateFinished.getType());
		tradeOfflineMapper.updateByPrimaryKeySelective(updateRecord);

		return result;
	}

	//单笔交易分润计算(异步执行)
	public int saveOneOrderProfitCalculate( final Long orderId) throws Exception{
		exec.submit((new Runnable() {
			@Override
			public void run() { 
				try {
					TradeOffline trade = tradeOfflineMapper.selectByPrimaryKey(orderId);
					if(trade==null){
						System.out.println("saveOneOrderProfitCalculate.TradeOffline is null ..."+orderId);
					}else{
						saveOneOrderProfitCalculate(trade);
					}
					
				}catch (Exception e){
                    logger.error(e);
                    e.printStackTrace();
				}
			}
		}));
		return 1;
	}


	//查询需要分润退款的交易记录	
	public List<TradeOffline> selectNeedProfitRefundList(Date selectDate) throws Exception{
		return tradeOfflineMapper.selectNeedProfitRefundList(selectDate);
	}
	
	//单笔交易分润退款处理
    public int saveOneOrderProfitRefund(TradeOffline record) throws Exception{
    	int result=0;
    	
		result = profitMapper.insertProfitRefundRecord(record.getId(),record.getOrderId()
    			, record.getOldOrderId(), "分润退款");

    	//更新退款记录
    	TradeOffline updateRecord = new TradeOffline();
    	updateRecord.setId(record.getId());
    	updateRecord.setGmtModified(new Date());
    	updateRecord.setAttachStatus(ProfitCalculateStatus.ProfitReturn.getType());
    	tradeOfflineMapper.updateByPrimaryKeySelective(updateRecord);
    	
        return result;
    }
	
    public int saveProfitDayStatis(Date statisDate) throws Exception{
    	int result=0;
    	//查询老记录
    	Map<String,Object> param=new HashMap<String,Object>();
		param.put("taskType", TaskType.ProfitDayStatis.getType());
		param.put("taskDate", statisDate);

		SysTaskLog oldRecord = sysTaskLogMapper.selectSysTaskLogByTypeAndDate(param);
        if(oldRecord  != null && oldRecord.getResultStatus() == RunStatus.Success.getType()){
        	throw new ApplicationException(Rescode.FAIL,"计划任务已经执行成功！");
        }

    	StringBuffer sb = new StringBuffer();
		//分润会员日统计
		result = profitMemberDayMapper.insertDayStatis(statisDate);
		sb.append("本次任务日统计【分润会员日统计】影响的行数：").append(result);
		//分润门店日统计
		result = profitShopDayDetailMapper.insertDayStatis(statisDate);
		sb.append("本次任务日统计【分润门店日统计】影响的行数：").append(result);
    	//分润代理日统计
    	result = profitAgentDayDetailMapper.insertDayStatis(statisDate);
    	sb.append("本次任务日统计【分润代理日统计】影响的行数：").append(result);
		//分润大商户日统计
		result = profitGroupDayDetailMapper.insertDayStatis(statisDate);
		sb.append("本次任务日统计【分润大商户日统计】影响的行数：").append(result);

    	//插入计划任务成功日志
        if(oldRecord  == null){
	    	SysTaskLog record = new SysTaskLog();
	    	record.setGmtCreate(new Date());
	    	record.setGmtModified(new Date());
	    	record.setTaskType(TaskType.ProfitDayStatis.getType());
	    	record.setTaskDate(statisDate);
	    	record.setResultStatus(RunStatus.Success.getType());
	    	record.setRunTimes(0);
	    	record.setMemo(sb.toString());
	    	result = sysTaskLogMapper.insert(record);
        }
        else{
        	oldRecord.setGmtModified(new Date());
        	oldRecord.setResultStatus(RunStatus.Success.getType());
        	oldRecord.setRunTimes((oldRecord.getRunTimes()==null?0:oldRecord.getRunTimes())+1);
        	oldRecord.setMemo(sb.toString());
        	result = sysTaskLogMapper.updateByPrimaryKeySelective(oldRecord);
        }

    	return result;
    }
    
    public int saveProfitMonthStatis(Date statisDate) throws Exception{
    	int result=0;
    	
    	Map<String,Object> param=new HashMap<String,Object>();
		param.put("taskType", TaskType.ProfitMonthStatis.getType());
		param.put("taskDate", statisDate);

		SysTaskLog oldRecord = sysTaskLogMapper.selectSysTaskLogByTypeAndDate(param);
        if(oldRecord  != null && oldRecord.getResultStatus() == RunStatus.Success.getType()){
        	throw new ApplicationException(Rescode.FAIL,"计划任务已经执行成功！");
        }

    	StringBuffer sb = new StringBuffer();

		//会员月统计
		result = profitMemberMonthMapper.insertMonthStatis(statisDate);
		sb.append("本次任务会员月统计影响的行数：").append(result);
    	//门店月统计
		result = profitShopMonthDetailMapper.insertMonthStatis(statisDate);
		sb.append(";本次任务门店月明细统计影响的行数：").append(result);
    	result = profitShopMonthMapper.insertMonthStatis(statisDate);
    	sb.append(";本次任务门店月统计影响的行数：").append(result);
    	//代理月统计
    	result = profitAgentMonthDetailMapper.insertMonthStatis(statisDate);
    	sb.append(";本次任务代理月明细统计影响的行数：").append(result);
		result = profitAgentMonthMapper.insertMonthStatis(statisDate);
		sb.append(";本次任务代理月统计影响的行数：").append(result);
		//大商户月统计
		result = profitGroupMonthDetailMapper.insertMonthStatis(statisDate);
		sb.append(";本次任务大商户月明细统计影响的行数：").append(result);
		result = profitGroupMonthMapper.insertMonthStatis(statisDate);
		sb.append(";本次任务大商户月统计影响的行数：").append(result);

    	//插入计划任务成功日志
        if(oldRecord  == null){
	    	SysTaskLog record = new SysTaskLog();
	    	record.setGmtCreate(new Date());
	    	record.setGmtModified(new Date());
	    	record.setTaskType(TaskType.ProfitMonthStatis.getType());
	    	record.setTaskDate(statisDate);
	    	record.setResultStatus(RunStatus.Success.getType());
	    	record.setRunTimes(0);
	    	record.setMemo(sb.toString());
	    	result = sysTaskLogMapper.insert(record);
        }
        else{
        	oldRecord.setGmtModified(new Date());
        	oldRecord.setResultStatus(RunStatus.Success.getType());
        	oldRecord.setRunTimes((oldRecord.getRunTimes()==null?0:oldRecord.getRunTimes())+1);
        	oldRecord.setMemo(sb.toString());
        	result = sysTaskLogMapper.updateByPrimaryKeySelective(oldRecord);
        }
    	
    	return result;
    }

	//分润打款月任务方法
	public int profitOutMontyMonth(Date statisDate) throws Exception{
		int result = 0;
		Map<String,Object> param=new HashMap<String,Object>();
		param.put("taskType", TaskType.ProfitOutMoneyMonthTask.getType());
		param.put("taskDate", statisDate);

		SysTaskLog oldRecord = sysTaskLogMapper.selectSysTaskLogByTypeAndDate(param);
		if(oldRecord  != null && oldRecord.getResultStatus() == RunStatus.Success.getType()){
			throw new ApplicationException(Rescode.FAIL,"计划任务已经执行成功！");
		}
		StringBuffer sb = new StringBuffer();

		//会员月出款
		List<ProfitMemberMonth> profitMemberMonthList = profitMemberMonthMapper.selectMemberProfitOutMoneyList(statisDate);
		sb.append("会员月出款记录数：").append(profitMemberMonthList==null?0:profitMemberMonthList.size());
		for(ProfitMemberMonth profitMemberMonth : profitMemberMonthList){
			profitManageService.updateMemberProfitOutMoney(profitMemberMonth,0L);
		}

		//门店月出款
		List<ProfitShopMonth> profitShopMonthList = profitShopMonthMapper.selectShopProfitOutMoneyList(statisDate);
		sb.append("门店月出款记录数：").append(profitShopMonthList==null?0:profitShopMonthList.size());
		for(ProfitShopMonth profitShopMonth : profitShopMonthList){
			profitManageService.updateShopProfitOutMoney(profitShopMonth,0L);
		}

		//代理月出款
		List<ProfitAgentMonth> profitAgentMonthList = profitAgentMonthMapper.selectAgentProfitOutMoneyList(statisDate);
		sb.append("代理月出款记录数：").append(profitAgentMonthList==null?0:profitAgentMonthList.size());
		for(ProfitAgentMonth profitAgentMonth : profitAgentMonthList){
			profitManageService.updateAgentProfitOutMoney(profitAgentMonth,0L);
		}

		//插入计划任务成功日志
		if(oldRecord  == null){
			SysTaskLog record = new SysTaskLog();
			record.setGmtCreate(new Date());
			record.setGmtModified(new Date());
			record.setTaskType(TaskType.ProfitOutMoneyMonthTask.getType());
			record.setTaskDate(statisDate);
			record.setResultStatus(RunStatus.Success.getType());
			record.setRunTimes(0);
			record.setMemo(sb.toString());
			result = sysTaskLogMapper.insert(record);
		}
		else{
			oldRecord.setGmtModified(new Date());
			oldRecord.setResultStatus(RunStatus.Success.getType());
			oldRecord.setRunTimes((oldRecord.getRunTimes()==null?0:oldRecord.getRunTimes())+1);
			oldRecord.setMemo(sb.toString());
			result = sysTaskLogMapper.updateByPrimaryKeySelective(oldRecord);
		}

		return result;
	}

}
